package com.inepex.inechart.client.linechart;

import java.util.ArrayList;

import com.inepex.inechart.shared.linechart.Curve;
import com.inepex.inegraphics.impl.client.DrawingAreaGWT;
import com.inepex.inegraphics.impl.client.IncrementalProgressCallerImpl;

public abstract class IncrementalLineChartDrawer{

	protected IncrementalProgressCallerImpl drawingAreaUpdater;
	protected LineChartGwt lineChartGwt;
	protected ArrayList<Curve> curves;
	protected DrawingAreaGWT actualTarget;
	protected int updatePartTreshold;
	protected boolean lineChartGos;


	public IncrementalLineChartDrawer(LineChartGwt lineChartGwt, ArrayList<Curve> curves, int updatePartTreshold) {
		super();
		this.lineChartGwt = lineChartGwt;
		this.curves = curves;
		this.updatePartTreshold = updatePartTreshold;
		lineChartGos = true;
		if(next()){
			startNext();
		}
		else{
			onFinish();
		}
	}
	
	protected void startNext(){
		drawingAreaUpdater = new IncrementalProgressCallerImpl(actualTarget, updatePartTreshold) {

			@Override
			public void onFinished() {
				if(next()){
					startNext();
				}
				else{
					onFinish();
				}
			}
		};
	}

	protected boolean next(){
		if(curves.size() > 0){
			Curve curve = curves.get(0);
			//TODO consider incremental GO to Canvas adding (e.g. may be a big chunk of time adding 10K objects...) 
			if(lineChartGos){
				actualTarget = lineChartGwt.getOrCreateLayerLCLayerForActualTile(curve);
				actualTarget.add(lineChartGwt.curveToGOMap.get(curve).lineChartGOs);
				lineChartGos = false;
			}
			else{
				actualTarget = lineChartGwt.getOrCreateLayerPCLayerForActualTile(curve);
				actualTarget.add(lineChartGwt.curveToGOMap.get(curve).pointChartGOs);
				lineChartGos = true;
				curves.remove(0);
			}
			return true;
		}
		else{
			return false;
		}
	}

	public abstract void onFinish();	
	

}
